<template>
    <addEditFaAssetsAloneView ref="addEditFaAssetsAloneView" />
    <addFileView ref="addFileView" />
    <addEditFaAssetsView ref="addEditFaAssetsView" />
    <addEditChaiFenView ref="addEditChaiFenView" />
    <addEditDelView ref="addEditDelView" />
    <el-main>
        <div class="teacher">
            <div class="app-table">
                <div class="app-body">
                    <div class="app-search">
                        <el-form :inline="true" class="demo-form-inline" v-model="addAssetsForm">
                            <el-form-item label="资产名称">
                                <el-input placeholder="请输入资产名称" v-model="addAssetsForm.name"
                                    @keyup.enter="searchEnter"></el-input>
                            </el-form-item>
                            <!-- <el-form-item label="地址信息">
                                <el-input placeholder="请输入地址信息" v-model="addAssetsForm.place"
                                    @keyup.enter="searchEnter"></el-input>
                            </el-form-item> -->

                            <!-- <el-form-item label="创建人">
                                <el-input placeholder="请输入创建人姓名" v-model="type"></el-input>
                            </el-form-item>
                            <el-form-item label="创建人工号">
                                <el-input placeholder="请输入创建人工号" v-model="type"></el-input>
                            </el-form-item> -->
                            <el-form-item>
                                <el-button class="serach_btn" type="primary" @click="onSubmit"
                                    @keyup.enter="searchEnter">搜索</el-button>
                                <!-- <el-button class="add_btn" type="success" @click="add">批量添加</el-button> -->
                                <el-upload class="upload-demo" :on-change="handleChange" :auto-upload="false"
                                    style="width: 90px; margin: 0 10px 0;" ref="upload" :show-file-list="false">
                                    <el-button class="add_btn" type="success" style="width: 90px;">批量添加</el-button>
                                </el-upload>
                                <el-button class="add_btn" type="success" @click="addOne">单个添加</el-button>
                                <el-button class="add_btn" type="success" @click="exportHandle">导出资产</el-button>
                                <el-upload class="upload-demo" :on-change="importOldCodeHandle1" :auto-upload="false"
                                    style="width: 110px; margin:  0 10px;" ref="upload" :show-file-list="false">
                                    <el-button class="add_btn" type="success" style="width: 110px;">更新财政编号</el-button>
                                </el-upload>
                                <el-button class="add_btn" type="success" @click="pringFileAll">批量打印条码</el-button>
                                <el-button class="add_btn" type="success" v-if="deleteFlag"
                                    @click="clearYaerAll">按年限删除</el-button>
                                <el-button class="add_btn" type="success" v-if="deleteFlag"
                                    @click="clearBatch">批量删除</el-button>
                                <el-button class="add_btn" type="success" @click="clearAll">清空</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                    <el-table :data="list" style="width: 100%" :row-class-name="tableRowClassName"
                        @selection-change="changeTableHandle">
                        <el-table-column type="selection" width="30" />
                        <el-table-column prop="company" label="归口单位" width="150" />
                        <el-table-column prop="name" label="资产名称" width="120" />
                        <el-table-column prop="code" label="资产编号" width="150" />
                        <el-table-column prop="oldCode" label="财政编号" width="150" />
                        <!-- <el-table-column prop="category" label="分类名称" />
                        <el-table-column prop="categoryCod" label="分类号" />
                        <el-table-column prop="standards" label="计量单位" /> -->
                        <el-table-column prop="model" label="型号" width="150" />
                        <el-table-column prop="price" label="单价" />
                        <el-table-column prop="amount" label="数量" />
                        <el-table-column prop="money" label="金额" />
                        <el-table-column prop="department" label="使用部门" />
                        <el-table-column prop="useTeacher" label="使用人"></el-table-column>
                        <el-table-column prop="managerDepartment" label="管理部门" />
                        <el-table-column prop="manager" label="管理人" />
                        <el-table-column prop="place" label="存放地点" width="180" />
                        <el-table-column label="操作" width="230px">
                            <template style="display: block" #default="scope">
                                <div style="display: flex;">
                                    <div>
                                        <el-button class="edit_btn" size="small" type="danger"
                                            @click="pringFile(scope.row)">打印条码
                                        </el-button>
                                        <el-button class="edit_btn" size="small" type="success"
                                            @click="editAssetsDetail(scope.row)">编辑
                                        </el-button>
                                        <el-button class="del_btn" size="small" type="danger"
                                            style="margin-right: 10px;" @click="deleteAssetsDetail(scope.row.id)">删除
                                        </el-button>
                                    </div>
                                    <!-- <div v-show="scope.row.amount > 1">
                                        <el-button class="edit_btn" size="small" type="success"
                                            style="margin-left: 10px;"
                                            v-show="scope.row.categoryCode != null && (scope.row.categoryCode.substring(0, 2) == 10 || scope.row.categoryCode.substring(0, 2) == 50 || scope.row.categoryCode.substring(0, 2) == 60 || scope.row.categoryCode.substring(0, 2) == 20)"
                                            @click=" goChaifen(scope.row, '组合拆分', '资产明细')">组合拆分
                                        </el-button>
                                        <el-button class="del_btn" size="small" type="danger"
                                            v-show="scope.row.categoryCode != null && (scope.row.categoryCode.substring(0, 2) != 10 && scope.row.categoryCode.substring(0, 2) != 50 && scope.row.categoryCode.substring(0, 2) != 60)"
                                            @click=" goChaifen(scope.row, '平均拆分', '资产明细')">平均拆分
                                        </el-button>
                                    </div> -->
                                </div>
                            </template>
                        </el-table-column>
                        <template v-slot:empty>
                            <el-empty description="暂无数据"></el-empty>
                        </template>
                    </el-table>
                    <el-config-provider :locale="locale">
                        <el-pagination :total="total" :page-size="limit" :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
                            layout="total, sizes, prev, pager, next, jumper" @size-change="changePageSize"
                            @current-change="changeCurrentPage">
                        </el-pagination>
                    </el-config-provider>
                </div>
                <bottomView />
            </div>
        </div>
    </el-main>
</template>
<script>
import addEditChaiFenView from "@/components/assets/chaiFen.vue";
import addEditFaAssetsAloneView from "@/components/assets/addEditFaAssetsAlone.vue";
import addEditFaAssetsView from "@/components/assets/addEditFaAssets.vue";
import addEditDelView from "@/components/assets/addEditDelView.vue";
import addFileView from "@/components/addExcelFile.vue";
import { ElConfigProvider, ElMessageBox, ElMessage, ElLoading } from "element-plus";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import { httpService } from "@/utils/httpService";
import { Picture as IconPicture, Upload } from "@element-plus/icons-vue";
import bottomView from "@/components/bottom.vue";
import * as XLSX from 'xlsx';
import { API_BASE_NAME, API_BASE_NAME1 } from '../../constants';

export default {
    name: "FaProjectListView",
    data() {
        return {
            type: 0,
            title: "",
            page: 1,
            pageSize: 10,
            total: 0,
            limit: 10,
            list: [],
            assetsList: [],
            expandedRowKeys: [],
            selectAllData: [],
            MyPermission: [],
            deleteFlag: false,
            idsAll: '',

            addAssetsForm: {
                name: "",
                code: "",
                oldCode: "",
                category: "",
                categoryCode: "",
                standards: "",
                model: "",
                price: "",
                amount: "",
                money: "",
                department: "",
                managerDepartment: "",
                manager: "",
                place: "",
            },
        };
    },
    components: {
        addEditFaAssetsAloneView,
        addEditChaiFenView,
        addEditFaAssetsView,
        addFileView,
        IconPicture,
        ElConfigProvider,
        ElMessageBox,
        ElMessage, Upload,
        bottomView, addEditDelView,
    },
    setup() {
        return {
            locale: zhCn,
        };
    },
    mounted() {
        this.getFaProjectList();
        this.getMyPermission()
    },
    watch: {
        $route() {
            this.getFaProjectList();
        },
    },
    methods: {
        searchEnter: function (e) {
            // 使用 which 和 keyCode 属性来解决兼容问题
            var keyCode = window.event ? e.keyCode : e.which;
            var val = e.target.value;
            if (keyCode == 13 && val) {
                this.getFaProjectList();
            }
        },
        // clearAll() {
        //     httpService("/javaApi/faSubList/deleteByYear", "year=" + 2024, "get").then(
        //         (data) => {
        //             console.log(data);
        //         }
        //     );
        // },
        getMyPermission() {
            httpService("/javaApi/getMyPermission", {}, "get").then(
                (data) => {
                    if (data) {
                        const arr = data.filter(item => item == "assetDeletionPermission")
                        if (arr.length > 0) {
                            this.deleteFlag = true
                        } else {
                            this.deleteFlag = false
                        }
                    }
                }
            );
        },
        importOldCodeHandle1(e) {
            var loadingInstance = ElLoading.service({
                lock: true, text: '加载中', background: 'rgba(0, 0, 0, 0.7)',
            });
            const file = e.raw;
            if (file) {
                loadingInstance.close()
            }
            const reader = new FileReader();

            reader.onload = (e) => {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });
                const sheet = workbook.Sheets[workbook.SheetNames[0]];
                const range = XLSX.utils.decode_range(sheet['!ref']);

                // 获取表头
                const headers = [];
                for (let col = range.s.c; col <= range.e.c; col++) {
                    const cell = sheet[XLSX.utils.encode_cell({ r: range.s.r, c: col })];
                    headers.push(cell ? cell.v : '');
                }
                // 获取财政资产编号列的索引
                const columnIndex = headers.findIndex(header => header === '财政资产编号');
                // 检查财政资产编号列是否有空的行，并打印空行的行数
                let emptyRows = [];
                for (let row = range.s.r + 1; row <= range.e.r; row++) {
                    const cell = sheet[XLSX.utils.encode_cell({ r: row, c: columnIndex })];
                    if (!cell || !cell.v) {
                        emptyRows.push(row + 1); // 添加到空行数组中
                    }
                }

                // 打印空行的行数
                if (emptyRows.length > 0) {
                    ElMessage.error("表头为财政资产编号的列不能为空，现有财政资产编号列为空的行数：" + emptyRows.join(', '));
                } else {
                    let params = new FormData()
                    params.append('file', file)
                    httpService("/javaApi/faSubList/updateOldCode", params, "post").then(
                        (data) => {
                            loadingInstance.close()
                            if (data.code == 200) {
                                ElMessage.success("导入成功");
                                this.getFaProjectList()
                            } else {
                                ElMessage.error("导入失败");
                            }
                        }
                    );
                }
            };

            reader.readAsArrayBuffer(file);

        },

        handleChange(e) {
            var loadingInstance = ElLoading.service({
                lock: true, text: '加载中', background: 'rgba(0, 0, 0, 0.7)',
            });
            const file = e.raw;
            if (file) {
                loadingInstance.close()
            }
            const reader = new FileReader();

            reader.onload = (e) => {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });
                // 获取第一个工作表
                const sheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[sheetName];
                // 定义要检查的列名
                const columnsToCheck = ['归口单位'];
                // 存储空行的信息
                const result = {};
                for (let rowNum = 2; ; rowNum++) { // 假设第一行是标题，从第二行开始遍历
                    const row = XLSX.utils.sheet_to_json(worksheet, { range: rowNum, header: 1 })[0];
                    if (!row || row.length === 0) {
                        break;
                    }
                    columnsToCheck.forEach((columnName, index) => {
                        if (!row[index]) {
                            // 记录空行的信息
                            if (!result[columnName]) {
                                result[columnName] = [];
                            }
                            result[columnName].push(rowNum);
                        }
                    });
                }
                console.log("result", result);
                if (JSON.stringify(result) != "{}") {
                    let resStr = ''
                    let resArr = []
                    for (let key in result) {
                        resStr = key + "列有空数据行：" + result[key].join(",")
                        // console.log(123,resStr);
                        resArr.push(resStr)
                    }
                    ElMessage.error(resArr.join("；"));
                } else {
                    let params = new FormData()
                    params.append('file', file)
                    httpService("/javaApi/faSubList/importExcel", params, "post").then(
                        (data) => {
                            loadingInstance.close()
                            if (data.code == 200) {
                                ElMessage.success("导入成功");
                                this.getFaProjectList()
                            } else {
                                ElMessage.error("导入失败");
                            }
                        }
                    );
                }
            };

            reader.readAsArrayBuffer(file);
        },
        pringFile(data) {
            console.log(data);
            let arr = [data]
            arr = arr.map(item => {
                if (item.purchaseDate != null && item.purchaseDate != '') {
                    return {
                        "资产名称": item.name,
                        "购进日期": item.purchaseDate.slice(0, 10),
                        "管理部门": item.managerDepartment,
                        "使用人": item.useTeacher,
                        "存放地点": item.place,
                        "资产编号": item.code,
                    }
                } else {
                    return {
                        "资产名称": item.name,
                        "购进日期": item.purchaseDate,
                        "管理部门": item.managerDepartment,
                        "使用人": item.useTeacher,
                        "存放地点": item.place,
                        "资产编号": item.code,
                    }

                }
            })
            const columnsWidth = [
                { wch: 20 },
                { wch: 15 },
                { wch: 15 },
                { wch: 15 },
                { wch: 30 },
                { wch: 25 },
            ];
            // const selectedData = tableData.value.filter(item => item._selected);
            const worksheet = XLSX.utils.json_to_sheet(arr);
            worksheet['!cols'] = columnsWidth;
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
            XLSX.writeFile(workbook, '条码.xlsx');
        },
        pringFileAll() {

            if (this.selectAllData.length == 0) {
                ElMessage({
                    showClose: true,
                    message: '请选择要打印的内容',
                    type: 'warning',
                })
            } else {
                const columnsWidth = [
                    { wch: 20 },
                    { wch: 15 },
                    { wch: 15 },
                    { wch: 15 },
                    { wch: 30 },
                    { wch: 25 },
                ];
                // const selectedData = tableData.value.filter(item => item._selected);
                const worksheet = XLSX.utils.json_to_sheet(this.selectAllData);
                worksheet['!cols'] = columnsWidth;
                const workbook = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
                XLSX.writeFile(workbook, '条码.xlsx');
            }
        },
        changeTableHandle(value) {
            let ids = value
            if (ids.length > 0) {
                this.idsAll = ids.map(val => val.id).join(",")
            }
            if (value) {
                this.selectAllData = value.map(item => {
                    if (item.purchaseDate != null && item.purchaseDate != '') {
                        return {
                            "资产名称": item.name,
                            "购进日期": item.purchaseDate.slice(0, 10),
                            "管理部门": item.managerDepartment,
                            "使用人": item.useTeacher,
                            "存放地点": item.place,
                            "资产编号": item.code,
                        }
                    } else {
                        return {
                            "资产名称": item.name,
                            "购进日期": item.purchaseDate,
                            "管理部门": item.managerDepartment,
                            "使用人": item.useTeacher,
                            "存放地点": item.place,
                            "资产编号": item.code,
                        }

                    }
                })
            }
        },
        clearAll() {
            ElMessageBox.confirm("确定要删除本条记录吗？", "提醒", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    let params = new FormData
                    httpService("/javaApi/faSubList/deleteAll", params, "post").then(
                        (data) => {
                            if (data.code == 200) {
                                ElMessage.success("删除成功");
                                this.getFaProjectList();
                            } else {
                                ElMessage.error("删除失败，请重试！");
                            }
                        }
                    );
                })
                .catch(() => {
                });
        },
        clearBatch() {
            ElMessageBox.confirm("确定要删除本条记录吗？", "提醒", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    httpService("/javaApi/faSubList/deleteOthers", "ids=" + this.idsAll, "post").then(
                        (data) => {
                            if (data.code == 200) {
                                ElMessage.success("删除成功");
                                this.idsAll = ""
                                this.getFaProjectList();
                            } else {
                                ElMessage.error("删除失败，请重试！");
                            }
                        }
                    );
                })
                .catch(() => {
                });
        },
        clearYaerAll() {
            this.$refs.addEditDelView.dialogFormVisible = true;
            this.$refs.addEditDelView.title = "按年限删除"
        },
        goChaifen(row, str, str1) {
            this.$refs.addEditChaiFenView.title = str
            this.$refs.addEditChaiFenView.name = str1
            this.$refs.addEditChaiFenView.personnelType = this.type
            this.$refs.addEditChaiFenView.dialogFormVisible = true;
            this.$refs.addEditChaiFenView.chaiFenData = row;
        },
        add() {
            // this.$refs.addEditFaAssetsView.title = "批量资产添加"
            // this.$refs.addEditFaAssetsView.personnelType = this.type
            // this.$refs.addEditFaAssetsView.dialogFormVisible = true;
        },
        addOne() {
            this.$refs.addEditFaAssetsAloneView.title = "单个资产添加"
            this.$refs.addEditFaAssetsAloneView.personnelType = this.type
            this.$refs.addEditFaAssetsAloneView.dialogFormVisible = true;
            this.$refs.addEditFaAssetsAloneView.addAssetsAloneForm = {};
            this.$refs.addEditFaAssetsAloneView.getBaseTeacherList()
            this.$refs.addEditFaAssetsAloneView.getBaseDepartment()
        },

        editAssetsDetail(obj) {
            this.$refs.addEditFaAssetsAloneView.title = "修改资产"
            this.$refs.addEditFaAssetsAloneView.personnelType = this.type
            this.$refs.addEditFaAssetsAloneView.dialogFormVisible = true;
            this.$refs.addEditFaAssetsAloneView.addAssetsAloneForm = obj;
            this.$refs.addEditFaAssetsAloneView.parentId = obj.id;
            this.$refs.addEditFaAssetsAloneView.getBaseDepartment()
            this.$refs.addEditFaAssetsAloneView.getBaseTeacherList()
        },
        deleteAssetsDetail(id) {
            ElMessageBox.confirm("确定要删除本条记录吗？", "提醒", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    httpService("/javaApi/faSubList/deleteById", "id=" + id, "post").then(
                        (data) => {
                            if (data.code == 200) {
                                ElMessage.success("删除成功");
                                this.getFaProjectList();
                            } else {
                                ElMessage.error("删除失败，请重试！");
                            }
                        }
                    );
                })
                .catch(() => {
                });
        },
        exportHandle() {
            var loadingInstance = ElLoading.service({
                lock: true, text: '加载中', background: 'rgba(0, 0, 0, 0.7)',
            });
            httpService("/javaApi/faSubList/exportFaSubList", {
                name: this.addAssetsForm.name.trim(),
                place: this.addAssetsForm.place.trim(),
                company: API_BASE_NAME1,
            }, "get").then(
                (data) => {
                    loadingInstance.close()
                    if (data.code == 200) {
                        window.open("https://wx.zhengzhong.cn" + data.message, '_blank')
                        // window.open(data.message, '_blank')
                    }
                }
            );
        },
        reloadData() {
            this.page = 1;
            this.getFaProjectList()
        },
        importExcel() {
            this.$refs.addFileView.dialogFormVisible = true;
            this.$refs.addFileView.title = "批量导入资产项目表";
            this.$refs.addFileView.uploadApiUrl = "/api/faProject/importExcel";
        },

        onSubmit() {
            this.getFaProjectList();
        },
        // 每页记录数改变，size：回调参数，表示当前选中的“每页条数”
        changePageSize(size) {
            this.pageSize = size;
            this.limit = size;
            this.getFaProjectList();
        },

        // 改变页码，page：回调参数，表示当前选中的“页码”
        changeCurrentPage(page) {
            this.page = page;
            this.getFaProjectList();
        },
        tableRowClassName({ row, rowIndex }) {
            return "";
        },
        getFaProjectList(id) {
            httpService(
                "/javaApi/faSubList/listTop/" + this.page + "/" + this.pageSize + "/0",
                {
                    name: this.addAssetsForm.name.trim(),
                    // place: this.addAssetsForm.place.trim(),
                    company: API_BASE_NAME1,
                },
                "get"
            ).then((data) => {
                this.list = data.list;
                this.total = data.total;
                this.pageCount = data.pages;
            });
        },
    },
};
</script>
<style scoped>
.el-main {
    padding: 0px;
}

.teacher-content {
    width: 100%;
}

.app-table {
    background: #eff3f5;
    padding: 10px;
}

.app_add {
    background-color: #fff;
    margin-bottom: 10px;
    padding: 10px;
}

.app-search {
    padding: 10px;
    background-color: #fff !important;
}

.app-separator {
    padding-top: 10px;
    padding-bottom: 20px;
    padding-left: 10px;
}

.app-body {
    background: white;
    padding: 20px 20px 10px 20px;
    margin-bottom: 10px;
    min-height: calc(100vh - 243px);
}

.el-table .warning-row {
    --el-table-tr-bg-color: var(--el-color-warning-lighter);
}

.el-table .success-row {
    --el-table-tr-bg-color: var(--el-color-success-lighter);
}

.el-pagination {
    text-align: center;
    padding: 20px 10px;
    background-color: #fff;
}

.serach_btn {
    background-color: #007EFF;
    color: #fff;
    border-radius: 8px;
    border: none;
    /* margin-bottom: 10px */
}

.add_btn {
    background-color: #00c78c;
    color: #fff;
    border-radius: 8px;
    border: none;
    /* margin-bottom: 10px */
}

.edit_btn {
    background-color: #fff;
    color: #007EFF;
    border: none;
}

.del_btn {
    background-color: #fff;
    color: #FF0000;
    border: none;
}

.print_btn {
    background-color: #fff;
    color: green;
    /* color: #24b68a; */
    border: none;
}
</style>
